package com.wpzf.ndhc.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.symmetric.SM4;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.ndhc.domain.WpSjTbjbxxNd2024;
import com.wpzf.ndhc.service.WpzfNdhcInfoTranslateService;
import com.wpzf.ndhc.utils.LogUtil;
import com.wpzf.ndhc.utils.MyObjectUtil;
import com.wpzf.zxhc.mapper.XjtbTbBaseMapper;
import com.wpzf.zxhc.service.impl.WpzfDockServiceImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.sqlite.mc.SQLiteMCSqlCipherConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/DataExchange")
public class WpzfNdhcInfoTranslateController {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Value("${tempath}")
    public String tempath;

    @Autowired
    public XjtbTbBaseMapper xjtbTbBaseMapper;

    @Autowired
    private WpzfNdhcInfoTranslateService wpzfNdhcInfoTranslateServiceImpl;

    ReentrantLock lock = new ReentrantLock();

    private final static String privateKey = "E4F22E79D141717AA63231A9DF53F4062545F17950BCB87B184B0128C6CC494E";
    private final static String publicKey = "04D33B320ED4819E4BC0CBE579EA8C1EC5D23A63922C3A62C7DF46EE800777363B3F97B3E103D47933052F793BA1C55EAB5826B58A886D9FFE2565F3C8EFCCD8B1";
    private final static String gtypublicKey = "04CF7CAE31B5130D1D5D1AC1DC2778D94533868A8D57FC02BBD97B688E07145DAAA96462DC83D9F348261F738D51C049770C43BA53B584917C9E30C6221B737CDD";
    private final static String certCode = "API32_YXK33YEGLXMUVMOYEQ43JWE4EU";

    private final static ResourceBundle rb2 = ResourceBundle.getBundle("config/log");
    private final static String logUrl = rb2.getString("logToTxtUrl.ndhcInfoTranslate.receiveNdTbInfo");


    @Log(title = "接收数据包 获取年度国土云图斑信息 DB包", businessType = BusinessType.OTHER)
    //接收数据包 获取季度图斑信息  增量 DB包格式  每次下发为增量
    @RequestMapping(value = "/receiveDataPackage", method = RequestMethod.POST)
    public Map<String, Object> receiveNdTbInfo(HttpServletRequest request,
                                               HttpServletResponse response,
                                               @RequestBody String requestBody) {
        Map<String, Object> rest = new HashMap<>();
        LogUtil.logToTxt("requestBody:" + requestBody, logUrl);

        // 获取响应头信息并存储到Map中
        Map<String, String> requestHeaders = new HashMap<>();
        // 获取所有请求头的名称
        Enumeration<String> headerNames = request.getHeaderNames();

        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();

            // 根据头名称获取对应的值
            String headerValue = request.getHeader(headerName);
            requestHeaders.put(headerName, headerValue);
        }

        String secret = requestHeaders.get("x-lc-secret") + "";
        LogUtil.logToTxt("x-lc-secret:" + secret, logUrl);

        String data = decryptData(requestBody, secret);
        LogUtil.logToTxt("参数：" + data, logUrl);

        JSONObject param = JSON.parseObject(data);

        Map<String, Object> params = new HashMap<>();
        params.put("secret", secret);
        params.put("requestbody", requestBody);
        params.put("data", data);
        params.put("submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
        params.put("xzqdm", param.get("regioncode"));
        params.put("count", param.get("count"));
        params.put("status", '0');
        params.put("log", "");
        params.put("code", '0');
        Integer i = wpzfNdhcInfoTranslateServiceImpl.saveDb(params);

        if (i > 0) {
            rest.put("code", 200);
            rest.put("data", "");
            rest.put("message", "已接收信息，准备下载文件。");
            rest.put("traceid", "");
        } else {
            rest.put("code", 500);
            rest.put("data", "");
            rest.put("message", "信息接收有误！");
            rest.put("traceid", "");
        }

        CompletableFuture.runAsync(() -> {
            try {
                lock.lock();// 获取锁
                Map<String, Object> m1 = new HashMap<>();
                List<Map<String, Object>> dbList1 = queryShengDb(m1);

                Gson gson1 = new Gson();
                String listToJsonString1 = gson1.toJson(dbList1);
                LogUtil.logToTxt("省级平台未推送数据：" + listToJsonString1, logUrl);

                for (Map<String, Object> db : dbList1) {
                    String xzqdm = db.get("xzqdm") + "";
                    JSONObject dbObject = JSON.parseObject(db.get("data") + "");

                    System.out.println("文件开始下载。");
                    String dbPath = dbObject.get("url").toString(); //db路径
                    if (!"".equals(dbPath) && dbPath.indexOf("http") == -1) {
                        dbPath = "http://" + dbPath;
                    }
                    String dbType = dbObject.get("code").toString(); //db路径 WPZF2024_ND  WPZF2024

                    String fileName = dbPath.substring(dbPath.lastIndexOf("/") + 1);
                    dbPath = downloadByIO(dbPath, tempath, fileName);
                    File file = new File(dbPath);

                    if (file.exists()) {
                        System.out.println("文件下载完成。");
                        String dbPassword = "";//db密码
                        String fileurl = "jdbc:sqlite:" + dbPath;
                        Connection connection = null;
                        //接收年底图斑
                        if (dbType.equals("WPZFNDTB2024")) {
                            dbPassword = param.get("password").toString();
                            System.out.println("接收年度图斑");
                            try {
                                connection = SQLiteMCSqlCipherConfig.getV3Defaults().withKey(dbPassword).build().createConnection(fileurl);
                                Statement statement = connection.createStatement();
                                statement.setQueryTimeout(30);  // set timeout to 30 sec.
                                try {
                                    if ("44".equals(xzqdm.substring(0, 2))) {
                                        //广东
                                        ResultSet gdRest = statement.executeQuery("select * from tbjbxx where xzqdm like '44%' ");
                                        List<Map<String, Object>> gdResultList = resultSetToListMap(gdRest);
                                        String gd = putGdNdTb(gdResultList);
                                        LogUtil.logToTxt("广东数据推送返回结果：" + gd, logUrl);

                                        JSONObject gdObject = JSON.parseObject(gd);

                                        Map<String, Object> gdMap = new HashMap<>();
                                        gdMap.put("uuid", db.get("uuid"));
                                        gdMap.put("status", "200".equals(gdObject.get("code") + "") == true ? "1" : "0");
                                        gdMap.put("log", gd);
                                        updateDbSheng(gdMap);
                                    } else if ("45".equals(xzqdm.substring(0, 2))) {
                                        //广西
                                        ResultSet gxRest = statement.executeQuery("select * from tbjbxx where xzqdm like '45%' ");
                                        List<Map<String, Object>> gxResultList = resultSetToListMap(gxRest);
                                        String gx = putGxNdTb(gxResultList);
                                        LogUtil.logToTxt("广西数据推送返回结果：" + gx, logUrl);

                                        JSONObject gxObject = JSON.parseObject(gx);

                                        Map<String, Object> gxMap = new HashMap<>();
                                        gxMap.put("uuid", db.get("uuid"));
                                        gxMap.put("status", "200".equals(gxObject.get("code") + "") == true ? "1" : "0");
                                        gxMap.put("log", gx);
                                        updateDbSheng(gxMap);
                                    }
                                } catch (Exception e) {
                                    System.err.println(e.getMessage());
                                }
                            } catch (Exception e) {
                                System.err.println(e.getMessage());
                            } finally {
                                try {
                                    if (connection != null)
                                        connection.close();
                                } catch (SQLException e) {
                                    System.err.println(e.getMessage());
                                }
                            }
                        } else {
                            System.out.println("dbType不在规定字典内");
                            LogUtil.logToTxt("dbType不在规定字典内", logUrl);
                        }
                    } else {
                        System.out.println("文件下载失败");
                        LogUtil.logToTxt("文件下载失败", logUrl);
                    }
                }

                Map<String, Object> m2 = new HashMap<>();
                List<Map<String, Object>> dbList2 = queryDb(m2);

                Gson gson2 = new Gson();
                String listToJsonString2 = gson2.toJson(dbList2);
                LogUtil.logToTxt("系统未入库数据：" + listToJsonString2, logUrl);

                for (Map<String, Object> db : dbList2) {
                    JSONObject dbObject = JSON.parseObject(db.get("data") + "");

                    System.out.println("文件开始下载。");
                    String dbPath = dbObject.get("url").toString(); //db路径
                    String dbType = dbObject.get("code").toString(); //db路径 WPZF2024_ND  WPZF2024

                    String fileName = dbPath.substring(dbPath.lastIndexOf("/") + 1);
                    dbPath = downloadByIO(dbPath, tempath, fileName);
                    File file = new File(dbPath);

                    if (file.exists()) {
                        System.out.println("文件下载完成。");
                        Integer tbcount = Integer.parseInt(dbObject.get("count").toString()); //图斑数量
                        String dbPassword = "";//db密码
                        String fileurl = "jdbc:sqlite:" + dbPath;
                        Connection connection = null;
                        //接收年底图斑
                        if (dbType.equals("WPZFNDTB2024")) {
                            dbPassword = dbObject.get("password").toString();
                            System.out.println("接收年度图斑");
                            String nf = dbType.substring(8);
                            List<WpSjTbjbxxNd2024> tbxxbxjNdDTOList = new ArrayList<>();
                            try {
                                connection = SQLiteMCSqlCipherConfig.getV3Defaults().withKey(dbPassword).build().createConnection(fileurl);
                                Statement statement = connection.createStatement();
                                statement.setQueryTimeout(30);  // set timeout to 30 sec.

                                try {
                                    //入库
                                    ResultSet rs = statement.executeQuery("select * from tbjbxx");
                                    while (rs.next()) {
                                        WpSjTbjbxxNd2024 model = new WpSjTbjbxxNd2024();
                                        model.setTbbsm(MyObjectUtil.objectIsNullToString(rs.getString("tbbsm")).toString());
                                        model.setXzqdm(MyObjectUtil.objectIsNullToString(rs.getString("xzqdm")).toString());
                                        model.setXzqmc(MyObjectUtil.objectIsNullToString(rs.getString("xzqmc")).toString());
                                        model.setXzdm(MyObjectUtil.objectIsNullToString(rs.getString("xzdm")).toString());
                                        model.setXzmc(MyObjectUtil.objectIsNullToString(rs.getString("xzmc")).toString());
                                        model.setJcbh(MyObjectUtil.objectIsNullToString(rs.getString("jcbh")).toString());
                                        model.setTblx(MyObjectUtil.objectIsNullToString(rs.getString("tblx")));
                                        model.setTbtz(MyObjectUtil.objectIsNullToString(rs.getString("tbtz")).toString());
                                        model.setHsx(MyObjectUtil.objectIsNullToString(rs.getString("hsx")).toString());
                                        model.setJcmj(MyObjectUtil.objectIsNullToDouble(rs.getString("jcmj")));
                                        model.setJctqmj(MyObjectUtil.objectIsNullToDouble(rs.getString("jctqmj")));
                                        model.setBz(MyObjectUtil.objectIsNullToString(rs.getString("bz")).toString());
                                        model.setDlrdnydmj(MyObjectUtil.objectIsNullToDouble(rs.getString("dlrdnydmj")));
                                        model.setDlrdgdmj(MyObjectUtil.objectIsNullToDouble(rs.getString("dlrdgdmj")));
                                        model.setQtnydmj(MyObjectUtil.objectIsNullToDouble(rs.getString("qtnydmj")));
                                        model.setDlrdjsydmj(MyObjectUtil.objectIsNullToDouble(rs.getString("dlrdjsydmj")));
                                        model.setDlrdwlydmj(MyObjectUtil.objectIsNullToDouble(rs.getString("dlrdwlydmj")));
                                        model.setNzy(MyObjectUtil.objectIsNullToString(rs.getString("nzy")).toString());
                                        model.setZjgxj(MyObjectUtil.objectIsNullToString(rs.getString("zjgxj")).toString());
                                        model.setXxydmj(MyObjectUtil.objectIsNullToString(rs.getString("xxydmj")).toString());
                                        model.setWly(MyObjectUtil.objectIsNullToString(rs.getString("wly")).toString());
                                        model.setZjgcj(MyObjectUtil.objectIsNullToString(rs.getString("zjgcj")).toString());
                                        model.setTdzz(MyObjectUtil.objectIsNullToString(rs.getString("tdzz")).toString());
                                        model.setGkfq(MyObjectUtil.objectIsNullToString(rs.getString("gkfq")).toString());
                                        model.setSsnydmj(MyObjectUtil.objectIsNullToString(rs.getString("ssnydmj")).toString());
                                        model.setLsydmj(MyObjectUtil.objectIsNullToString(rs.getString("lsydmj")).toString());
                                        model.setFist_kyq(MyObjectUtil.objectIsNullToString(rs.getString("fist_kyq")).toString());
                                        model.setJbntmj(MyObjectUtil.objectIsNullToDouble(rs.getString("jbntmj")));
                                        model.setStbhhxmj(MyObjectUtil.objectIsNullToDouble(rs.getString("stbhhxmj")));
                                        model.setSxsj(MyObjectUtil.objectIsNullToString(rs.getString("sxsj")).toString());
                                        model.setHsxdz(MyObjectUtil.objectIsNullToString(rs.getString("hsxdz")).toString());
                                        model.setHsxdz_tif(MyObjectUtil.objectIsNullToString(rs.getString("hsxdz_tif")).toString());
                                        model.setHyjg_url(MyObjectUtil.objectIsNullToString(rs.getString("hyjg_url")).toString());
                                        model.setLongitude(MyObjectUtil.objectIsNullToDouble(rs.getString("longitude")));
                                        model.setLatitude(MyObjectUtil.objectIsNullToDouble(rs.getString("latitude")));
                                        model.setShape(MyObjectUtil.objectIsNullToString(rs.getString("shape")).toString());
                                        model.setMaxx(MyObjectUtil.objectIsNullToDouble(rs.getString("maxx")));
                                        model.setMinx(MyObjectUtil.objectIsNullToDouble(rs.getString("minx")));
                                        model.setMaxy(MyObjectUtil.objectIsNullToDouble(rs.getString("maxy")));
                                        model.setMiny(MyObjectUtil.objectIsNullToDouble(rs.getString("miny")));
                                        model.setSjdrly(MyObjectUtil.objectIsNullToString(rs.getString("sjdrly")).toString());
                                        model.setCreatetime(MyObjectUtil.objectIsNullToString(rs.getString("createtime")).toString());
                                        model.setModifytime(MyObjectUtil.objectIsNullToString(rs.getString("modifytime")).toString());
                                        model.setPch("年度卫片");
                                        model.setOp_time((new Date()).toString());
                                        tbxxbxjNdDTOList.add(model);
                                    }
                                    LogUtil.logToTxt("图斑数量:" + tbxxbxjNdDTOList.size(), logUrl);

                                    deleteTbxxbxjNd2024(tbxxbxjNdDTOList);

                                    Integer b = saveTbxxbxjNd2024(tbxxbxjNdDTOList);
                                    if (b > 0) {
                                        if (tbcount.equals(tbxxbxjNdDTOList.size())) {
                                            LogUtil.logToTxt("年度图斑导入成功" + tbxxbxjNdDTOList.size(), logUrl);

                                            Map<String, Object> m = new HashMap<>();
                                            m.put("uuid", db.get("uuid"));
                                            m.put("code", "1");
                                            updateDb(m);
                                        } else {
                                            System.out.println("年度图斑数量导入不一致" + tbxxbxjNdDTOList.size() + "/" + tbcount);
                                            LogUtil.logToTxt("年度图斑数量导入不一致" + tbxxbxjNdDTOList.size() + "/" + tbcount, logUrl);
                                        }
                                    } else {
                                        System.out.println("年度图斑导入失败");
                                        LogUtil.logToTxt("年度图斑导入失败", logUrl);
                                    }
                                } catch (Exception e) {
                                    LogUtil.logToTxt("入库失败", logUrl);
                                    System.err.println(e.getMessage());
                                }
                            } catch (Exception e) {
                                System.err.println(e.getMessage());
                            } finally {
                                try {
                                    if (connection != null)
                                        connection.close();
                                } catch (SQLException e) {
                                    System.err.println(e.getMessage());
                                }
                            }
                        } else {
                            System.out.println("dbType不在规定字典内");
                            LogUtil.logToTxt("dbType不在规定字典内", logUrl);
                        }
                    } else {
                        System.out.println("文件下载失败");
                        LogUtil.logToTxt("文件下载失败", logUrl);
                    }
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            } finally {
                lock.unlock();// 释放锁
            }
        });
        return rest;
    }

    private List<Map<String, Object>> queryShengDb(Map<String, Object> map) {
        return wpzfNdhcInfoTranslateServiceImpl.queryShengDb(map);
    }

    private List<Map<String, Object>> queryDb(Map<String, Object> map) {
        return wpzfNdhcInfoTranslateServiceImpl.queryDb(map);
    }

    private Integer updateDbSheng(Map<String, Object> map) {
        return wpzfNdhcInfoTranslateServiceImpl.updateDbSheng(map);
    }

    private Integer updateDb(Map<String, Object> map) {
        return wpzfNdhcInfoTranslateServiceImpl.updateDb(map);
    }

    public static String downloadByIO(String url, String saveDir, String fileName) {
        BufferedOutputStream bos = null;
        InputStream is = null;
        try {
            byte[] buff = new byte[8192];
            is = new URL(url).openStream();
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count = 0;
            while ((count = is.read(buff)) != -1) {
                bos.write(buff, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return saveDir + "\\" + fileName;
    }

    @Transactional
    public Integer deleteTbxxbxjNd2024(List<WpSjTbjbxxNd2024> wpSjTbjbxxNd2024List) {
        Integer rest = 0;
        for (WpSjTbjbxxNd2024 wpSjTbjbxxNd2024 : wpSjTbjbxxNd2024List) {
            rest += wpzfNdhcInfoTranslateServiceImpl.deleteTbxxbxjNd2024(wpSjTbjbxxNd2024);
        }
        return rest;
    }

    @Transactional
    public Integer saveTbxxbxjNd2024(List<WpSjTbjbxxNd2024> wpSjTbjbxxNd2024List) {
        Integer rest = 0;
        for (WpSjTbjbxxNd2024 wpSjTbjbxxNd2024 : wpSjTbjbxxNd2024List) {
            rest += wpzfNdhcInfoTranslateServiceImpl.saveTbxxbxjNd2024(wpSjTbjbxxNd2024);
        }
        return rest;
    }

    private Random random = new Random();

    //获取国土云token
    public String getGTYToken() {
        long timestamp = System.currentTimeMillis();

        //SM2
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
        //拼接待签名数据
        String needSignData = certCode + timestamp;
        byte[] needSignDataByte = needSignData.getBytes(StandardCharsets.UTF_8);
        //签名
        byte[] signData = sm2.sign(needSignDataByte);
        String signDataHex = HexUtil.encodeHexStr(signData);
        System.out.println("sign Hex:" + signDataHex);
        String signDataBase64 = Base64.encode(signData);
        System.out.println("sign Base64:" + signDataBase64);
        //生成token
        String token = certCode + "." + timestamp + "." + signDataBase64;
//        对于云上数据的存储资源访问或者存储时，建议采用私有模式，需要访问时，可对相关资源进行
//        临时鉴权，提供临时的上传地址和临时的访问地址。
        System.out.println("token:" + token);

        return token;
    }

    public static void main(String[] args) {
        String s = decryptData("yhXW5ezSh0CjwkYeq6tEPNS1vdlrcCiVocv9hT9JpQYh41lESYPB4JWmh4aysVBf4+5RoiNQhAjvOssuXwSnTyvD" +
                        "opZAhdllqYO5Wezik7xi3sNJXcY7VApg5J7HYaVCvb3+VNEhb0dg3Ujaq67z37GxvDtIHotGhr2r6G" +
                        "bnTziNxhBNX+ZDuGgBxs1X2yj+efhequVChXWoYGCJfrh1cbrtONhP5S9D5j3C9l2xl1SN9TtoMWHs7e8" +
                        "yd8f9OEhF6KdadZMH0sWqmN56MG5HJFt71nu8u4tf4pdfb0nNT5gy7ujXiZBJ0lL7B0WV6/GDbz/wzgFc" +
                        "jhWY/5Sx4aCBydf44k3SB4eW7wgQfcjp9x5G03Ye+LrTEwJHgbGqswN8NrsfHcDWI2hqM9zlGI0Web/pE0" +
                        "pdcFFT0r4AR0geaVGJ7sZ819CYEfGNJFjn3mm5AaLnbroFbaOuSLgdUR2j8Auigg9tuxhsU0YXVmOBIW3Qkr" +
                        "E8uRYhDranTBgwGPD9",
                "BBtIFrxxMHymcbTSTmVdFfcfWW0LhIOlgmSN5OER82sr7zmAxYhkFVousV0v4BLgFhMRdoLdCDx8mOPPcRnaX3ip2x2T25mtTebDDs+V+52POffPDfWjtZi8g9nbW3RuK5X6/M8otKyLBZVPW6Y9gyw=");
        System.out.println(s);
    }

    //解密国土云数据
    public static String decryptData(String data, String secret) {
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
        //SM2 解密SM4密钥
        byte[] decode = sm2.decrypt(secret, KeyType.PrivateKey);
        //SM4解密内容
        SM4 sm4 = new SM4(decode);
        byte[] sm4DataByte = sm4.decrypt(data);
        System.out.println("SM4 encrypt UTF-8:" + new String(sm4DataByte, StandardCharsets.UTF_8));
        return new String(sm4DataByte, StandardCharsets.UTF_8);
    }

    //ResultSet类型转为List
    public static List<Map<String, Object>> resultSetToListMap(ResultSet resultSet) throws SQLException {
        List<Map<String, Object>> list = new ArrayList<>();

        // 获取结果集的元数据，用于获取列名等信息
        java.sql.ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        while (resultSet.next()) {
            Map<String, Object> rowMap = new HashMap<>();

            for (int i = 1; i <= columnCount; i++) {
                // 获取列名
                String columnName = metaData.getColumnName(i);
                // 获取对应列的值
                Object columnValue = resultSet.getObject(i);

                rowMap.put(columnName, columnValue);
            }

            list.add(rowMap);
        }

        return list;
    }


    //广西图斑接收接口
    public String putGxNdTb(List<Map<String, Object>> resultList) {
        List<Map<String, Object>> list = new ArrayList<>();
        // 此时resultList就是转换后的包含查询结果的列表，可以根据需要进一步处理
        for (Map<String, Object> row : resultList) {
            String createtime = subStringUtil(row.get("createtime").toString());
            row.remove("createtime");
            row.put("createTime", createtime);
            list.add(row);
        }

        StringBuilder result = new StringBuilder();
        ModelMap map = new ModelMap();
        try {
            String token = getGxToken();
            // 创建Gson对象
            Gson gson = new Gson();

            // 将List转换为JSON字符串
            String data = gson.toJson(list);
            System.out.println(data);

            String postURL = "https://map.dnr.gxzf.gov.cn/zrzytcjc/wpzf/ndtb/create_ndwp_list";
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Src", "web");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Authorization", token);

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            result.append(new String(datas, 0, datas.length, "utf-8"));
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        return result.toString();
    }

    private static String getGxToken() {
        ModelMap map = new ModelMap();
        String result = null;
        try {
            String phonenumber = "13269013075";
            String password = WpzfDockServiceImpl.encryptPassword("zrzy@2024ST%!");
            String data = "{\"phonenumber\": \"" + phonenumber + "\",\"password\": \"" + password + "\"}";
            System.out.println(data);

            String postURL = "https://map.dnr.gxzf.gov.cn/zrzytcjc/loginPhoneApp";
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            result = new String(datas, 0, datas.length, "utf-8");
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
        Map mapType = JSON.parseObject(result, Map.class);
        String token = mapType.get("token") + "";

        return token;
    }

    //时间格式裁切
    public String subStringUtil(String str) {
        int dotIndex = str.indexOf('.');
        if (dotIndex == -1) {
            return str;
        } else {
            return str.substring(0, dotIndex);
        }
    }

    //广东图斑接收接口
    public String putGdNdTb(List<Map<String, Object>> resultList) {
        StringBuilder result = new StringBuilder();
        ModelMap map = new ModelMap();
        try {
            String token = getGxToken();
            // 创建Gson对象
            Gson gson = new Gson();

            // 将List转换为JSON字符串
            String data = gson.toJson(resultList);
            System.out.println(data);

            String postURL = "http://210.76.85.37/GwWpzf/receive";
            URL url = new URL(postURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Src", "web");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("x-tsp-appsecret", "cdf32528ddcb40acbc72439bdd0a4810");
            conn.setRequestProperty("x-tsp-paasid", "1600678502258008065");
            conn.setRequestProperty("x-tsp-serviceid", "DGSP_94c218b5-be9b-4120-b56c-3ac2cedad3d1");

            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

            out.write(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            int count = 0;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            while ((count = is.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, count);
            }
            byte[] datas = byteArrayOutputStream.toByteArray();

            byteArrayOutputStream.close();
            //关闭流
            is.close();

            conn.disconnect();
            result.append(new String(datas, 0, datas.length, "utf-8"));
        } catch (MalformedURLException ex) {
            throw new RuntimeException(ex);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        return result.toString();
    }

    //公钥加密
    @Test
    public void t1() {
        //(1)生成适用于SM4算法的随机密钥C sm4Key（128bit）
        byte[] keyC = SecureUtil.generateKey("SM4").getEncoded();

        //(2)使用密钥C，采用SM4算法对接口参数进行加密并编译成base64编码
        String data = "{\"code\":\"WPZFNDTB2024\",\"regioncode\":\"451481\",\"version\":1,\"size\":18432,\"count\":5,\"attachment_count\":null,\"extension\":\"db\",\"password\":\"ur19xrI2viRVNrR\",\"hash\":\"A01B6F3A99C5413BAFBF6BCA46952167453A0A77EBB27087EDDB4D2479EF35D9\",\"timestamp\":1734991310,\"sign\":\"5D7516863FBB7E11026D0A914BF547498F941C021F26FA40835B523C16DF749E9FB9A13D5DFE33806797BB2F37452D4824516D6D547A852B9AA01AD49B9A7A47\",\"url\":\"obs.cn-north-1.myhuaweicloud.com/gdhc-gj-012035/Temp/WPZFNDTB2024/20241224/451481/12100000400010398P/451481_20241224060147.db\"}";
        System.out.println("原始参数:" + data);

        byte[] dataByte = data.getBytes(StandardCharsets.UTF_8);

        SM4 sm4 = new SM4(keyC);
        byte[] sm4EncryptDataByte = sm4.encrypt(dataByte);
        String params = Base64.encode(sm4EncryptDataByte);
        System.out.println("参数加密后:" + Base64.encode(sm4EncryptDataByte));

        //(3)使用服务提供方的公钥B，采用SM2加密算法对密钥C进行加密并编码成base64写入Header的x-lc-secret中
//        SM2 sm2 = new SM2(null, gtypublicKey);
        SM2 sm2 = new SM2(null, publicKey);
        sm2.usePlainEncoding();
        byte[] sm2EncryptDataByte = sm2.encrypt(keyC, KeyType.PublicKey);
        String secret = Base64.encode(sm2EncryptDataByte);
        System.out.println("输入secret:" + secret);
    }


    @RequestMapping(value = "/pushNdSjDk", method = RequestMethod.POST)
    public AjaxResult pushNdSjDk(@RequestBody Map<String, Object> params) {
        try {
            Integer rest = wpzfNdhcInfoTranslateServiceImpl.pushNdSjDk(params);
            /*ReentrantLock lock2 = new ReentrantLock();
            Gson gson = new Gson();
            CompletableFuture.runAsync(() -> {
                try {
                    lock2.lock();// 获取锁

                    logText2("\n");
                    logText2("线程开始：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));

                    //查询状态为0的
                    List<Map<String, Object>> impList1 = queryStatusdk();
                    if (impList1 != null && impList1.size() > 0) {
                        for (int i = 0; i < impList1.size(); i++) {
                            logText2("第"+(i+1)+"条数据开始：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));

                            Map<String, Object> imp = impList1.get(i);
                            logText2(imp.get("params").toString());
                            WpsjdkDTO wpsjdkDTO = gson.fromJson(imp.get("params").toString(), WpsjdkDTO.class);
                            //存储地块 附件 批文信息
                            AjaxResult ajaxResult = getnddkxxbsjInfo2024(wpsjdkDTO);
                            if (ajaxResult.get("code").equals(200)) {
                                logText2(ajaxResult.get("code").toString());
                                //更新状态
                                int k = wpzfNdhcInfoTranslateServiceImpl.updateStatusdk(imp);
                                if (k > -1) {
                                    logText2("状态更新成功," + k);
                                }
                            } else {
                                logText2("地块处理失败");
                            }

                            logText2("第"+(i+1)+"条数据结束：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
                        }
                    }
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                } finally {
                    logText2("线程结束：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
                    lock2.unlock();// 释放锁
                }
            });*/
            if (rest > 0) {
                return AjaxResult.success("保存成功");

            } else {
                return AjaxResult.error("保存失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("保存失败", e);
        }
    }

    public List<Map<String, Object>> queryStatusdk() {
        return wpzfNdhcInfoTranslateServiceImpl.queryStatusdk();
    }

}


